#!/usr/bin/env python
# coding: UTF-8

import os
from os.path import exists
import sys
import bsddb
from itertools import groupby
import string
import optparse

TABLE = string.maketrans('actg', 'tgac')

def complement(s):
    return s.translate(TABLE)

def reverse_str(s):
    return ''.join(reversed(s))

def transparent(s):
    return reverse_str(complement(s))


def main():

    parser = optparse.OptionParser(
        usage = '%prog -g GENES_DB -G GENOMES_DB',
    )
    parser.add_option(
        '-g',
        dest = 'genes_db',
    )
    parser.add_option(
        '-G',
        dest = 'genomes_db',
    )
    opts, args = parser.parse_args()
    if not (opts.genes_db and opts.genomes_db):
        print >> sys.stderr, parser.usage
        sys.exit(1)
        
    if not (exists(opts.genomes_db) and exists(opts.genes_db)):
        print >> sys.stderr, "Db doesn't exist!"
        sys.exit(2)
    
    genomes_db = bsddb.btopen(opts.genomes_db, 'r')
    genes_db = bsddb.btopen(opts.genes_db, 'r')
    
    genome_id = sys.stdin.readline().strip()
    genome = genomes_db[genome_id]
    sys.stdout.write("%s\t%s\n" % (genome_id, genome))
    glength = len(genome)

    prev_gene_id = None
    
    for line in sys.stdin:
        gene_id, gene_start, gene_end, genome_start, genome_end = line.split()
        if gene_id != prev_gene_id:
            gene = genes_db[gene_id]
        length = len(gene)
        if length >= 10000 or length <= 100:
            continue

        gene_start  = int(gene_start)
        gene_end    = int(gene_end)
        genome_start = int(genome_start)
        genome_end   = int(genome_end)
        
        if genome_start > genome_end:
            gene = transparent(gene)
            genome_start, genome_end = genome_end, genome_start
        if gene_start > gene_end:
            gene = transparent(gene)
            gene_start, gene_end = gene_end, gene_start
            
        # позиция первого символа гена в геноме для глобального выравнивания
        genome_global_start = genome_start - gene_start + 1
        if genome_global_start <= 0: genome_global_start = 1
        if genome_global_start+length-1 > glength: genome_global_start -= (genome_global_start+length-glength-1)
            
        sys.stdout.write("%s\t%s\t%s\n" % (gene_id, genome_global_start, gene))


if __name__ == '__main__':
    main()

